﻿using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;

namespace WinExamReader
{
    class WordHelper
    {
        public static DataTable ReadAnswer(string wordPath)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id");
            dt.Columns.Add("answer");

            Stream stream = File.OpenRead(wordPath);
            XWPFDocument doc = new XWPFDocument(stream);
            Console.WriteLine(doc.Tables.Count);

            try
            {
                for (int i = 0; i < doc.Tables.Count; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr["id"] = i + 1;
                    XWPFTable table = doc.Tables[i];
                    //寻找正确答案
                    foreach (XWPFTableRow row in table.Rows)
                    {
                        if (row.GetCell(0).GetText().Equals("标准答案"))//找到答案那一行
                        {
                            dr["answer"] = row.GetCell(1).GetText();
                            break;
                        }                        
                    }
                    if (dr["answer"] == DBNull.Value || dr["answer"] == null)
                    {
                        throw new Exception("未能获取到编号" + dr["id"] + "的正确答案");
                    }
                    dt.Rows.Add(dr);
                }
            }
            finally
            {
                doc.Close();
            }            
            return dt;
        }
    }
}
